package com.example.demo;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

import java.io.*;

/**
 * <p>
 * 测试生成代码
 * </p>
 *
 * @author K神
 * @date 2017/12/18
 */
public class GeneratorServiceEntity {

    @Test
    public void generateCode() {
        String packageName = "com.example.demo";
        boolean serviceNameStartWithI = false;//user -> UserService, 设置成true: user -> IUserService
        generateByTables(serviceNameStartWithI, packageName, "user", "role");
    }

    private void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
        GlobalConfig config = new GlobalConfig();
        String dbUrl = "jdbc:mysql://localhost:3306/mybatis-plus";
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername("root")
                .setPassword("")
                .setDriverName("com.mysql.jdbc.Driver");
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true)
                .setEntityLombokModel(false)
                .setDbColumnUnderline(true)
                .setNaming(NamingStrategy.underline_to_camel)
                .setInclude(tableNames);//修改替换成你需要的表名，多个表名传数组
        config.setActiveRecord(false)
                .setAuthor("K神带你飞")
                .setOutputDir("d:\\codeGen")
                .setFileOverride(true);
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }
        new AutoGenerator().setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(
                        new PackageConfig()
                                .setParent(packageName)
                                .setController("controller")
                                .setEntity("entity")
                ).execute();
    }

    private void generateByTables(String packageName, String... tableNames) {
        generateByTables(true, packageName, tableNames);
    }

    @Test
    public void startJPA() throws IOException {

        String packName = "qy"; // 包名
        String modelName = "Order";
        String projectPath = "D:\\liqingyou\\projects\\SpringBoot\\shop\\src\\main\\java";

        writeFile(projectPath + "\\com\\example\\demo\\" + packName + "\\dao\\" + modelName + "Dao.java" ,makeDao(packName,modelName));
        writeFile(projectPath + "\\com\\example\\demo\\" + packName+ "\\service\\" + modelName + "Service.java" ,makeService(packName,modelName));
        writeFile(projectPath + "\\com\\example\\demo\\" + packName+ "\\serviceimpl\\" + modelName + "ServiceImpl.java" ,makeServiceImpl(packName,modelName));
        writeFile(projectPath + "\\com\\example\\demo\\" + packName + "\\controller\\" + modelName + "Controller.java" ,makeController(packName,modelName));

    }

    public String makeDao(String packName,String clazzName) {
        String temp = "package com.example.demo." + packName + ".dao;\n" +
                "\n" +
                "import com.example.demo.base.BaseDao;\n" +
                "import com.example.demo." + packName + ".model." + clazzName + ";\n" +
                "\n" +
                "public interface " + clazzName + "Dao extends BaseDao<" + clazzName + ",String> {\n" +
                "\n" +
                "}";
        return temp;
    }
    public String makeService(String packName,String clazzName) {
        String temp = "package com.example.demo." + packName + ".service;\n" +
                "\n" +
                "import com.example.demo.base.BaseService;\n" +
                "import com.example.demo." + packName +".model." + clazzName + ";\n" +
                "\n" +
                "public interface " + clazzName + "Service extends BaseService<" + clazzName + ",String> {\n" +
                "}";
        return temp;
    }
    public String makeServiceImpl(String packName,String clazzName){
        String temp = "package com.example.demo." + packName + ".serviceimpl;\n" +
                "\n" +
                "import com.example.demo." + packName + ".dao." + clazzName + "Dao;\n" +
                "import com.example.demo." + packName + ".service." + clazzName + "Service;\n" +
                "import org.springframework.beans.factory.annotation.Autowired;\n" +
                "import org.springframework.stereotype.Service;\n" +
                "\n" +
                "@Service\n" +
                "public class " + clazzName + "ServiceImpl implements " + clazzName + "Service {\n" +
                "\n" +
                "    @Autowired\n" +
                "    private " + clazzName + "Dao " + clazzName + "Dao;\n" +
                "\n" +
                "    @Override\n" +
                "    public " + clazzName + "Dao getRepository() {\n" +
                "        return " + clazzName + "Dao;\n" +
                "    }\n" +
                "\n" +
                "}";
        return temp;
    }
    public String makeController(String packName,String modelName) {
        String temp = "package com.example.demo." + packName + ".controller;\n" +
                "\n" +
                "import com.example.demo.common.utils.PageUtil;\n" +
                "import com.example.demo.common.utils.ResultUtil;\n" +
                "import com.example.demo.common.vo.PageVo;\n" +
                "import com.example.demo.common.vo.Result;\n" +
                "import com.example.demo." + packName + ".model." + modelName + ";\n" +
                "import com.example.demo." + packName + ".service." + modelName + "Service;\n" +
                "import io.swagger.annotations.Api;\n" +
                "import io.swagger.annotations.ApiOperation;\n" +
                "import org.springframework.beans.factory.annotation.Autowired;\n" +
                "import org.springframework.data.domain.Page;\n" +
                "import org.springframework.web.bind.annotation.*;\n" +
                "\n" +
                "import java.util.List;\n" +
                "\n" +
                "@Api(value = \"" + modelName + "\")\n" +
                "@RestController\n" +
                "public class " + modelName + "Controller {\n" +
                "\n" +
                "    @Autowired\n" +
                "    private " + modelName + "Service " + lowerCase(modelName) + "Service;\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/get/{id}\",method = RequestMethod.GET)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"通过id获取\")\n" +
                "    public Result<" + modelName + "> get(@PathVariable String id){\n" +
                "        " + modelName + " entity = " + lowerCase(modelName) + "Service.get(id);\n" +
                "        return new ResultUtil<" + modelName + ">().setData(entity);\n" +
                "    }\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/getAll\",method = RequestMethod.GET)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"获取全部数据\")\n" +
                "    public Result<List<" + modelName + ">> getAll(){\n" +
                "        List<" + modelName + "> list = " + lowerCase(modelName) + "Service.getAll();\n" +
                "        return new ResultUtil<List<" + modelName + ">>().setData(list);\n" +
                "    }\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/getByPage\",method = RequestMethod.GET)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"分页获取\")\n" +
                "    public Result<Page<" + modelName + ">> getByPage(@ModelAttribute PageVo page){\n" +
                "        Page<" + modelName + "> list = " + lowerCase(modelName) + "Service.findAll(PageUtil.initPage(page));\n" +
                "        return new ResultUtil<Page<" + modelName + ">>().setData(list);\n" +
                "    }\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/save\",method = RequestMethod.POST)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"保存数据\")\n" +
                "    public Result<" + modelName + "> save(@ModelAttribute " + modelName + " entity){\n" +
                "        " + modelName + " e = " + lowerCase(modelName) + "Service.save(entity);\n" +
                "        return new ResultUtil<" + modelName + ">().setData(e);\n" +
                "    }\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/update\",method = RequestMethod.POST)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"更新数据\")\n" +
                "    public Result<" + modelName + "> update(@ModelAttribute " + modelName + " entity){\n" +
                "        " + modelName + " e = " + lowerCase(modelName) + "Service.update(entity);\n" +
                "        return new ResultUtil<" + modelName + ">().setData(e);\n" +
                "    }\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/del\",method = RequestMethod.DELETE)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"删除数据\")\n" +
                "    public Result<Object> delAll(@ModelAttribute " + modelName + " entity){\n" +
                "        " + lowerCase(modelName) + "Service.delete(entity);\n" +
                "        return new ResultUtil<Object>().setSuccessMsg(\"删除数据成功\");\n" +
                "    }\n" +
                "\n" +
                "    @RequestMapping(value = \"/" + modelName + "/delByIds\",method = RequestMethod.DELETE)\n" +
                "    @ResponseBody\n" +
                "    @ApiOperation(value = \"批量通过ids删除\")\n" +
                "    public Result<Object> delAllByIds(@RequestParam String[] ids){\n" +
                "        for(String id:ids){\n" +
                "            " + lowerCase(modelName) + "Service.delete(id);\n" +
                "        }\n" +
                "        return new ResultUtil<Object>().setSuccessMsg(\"批量删除数据成功\");\n" +
                "    }\n" +
                "\n" +
                "}\n";
        return temp;
    }

    /**
     * 首字母大写
     * @param str
     * @return
     */
    public String upperCase(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    /**
     * 首字符小写
     * @param str
     * @return
     */
    public String lowerCase(String str) {
        return str.substring(0, 1).toLowerCase() + str.substring(1);
    }

    void writeFile(String path,String str) throws IOException {
        try {
            // File file = new File("d:\\file.txt");
            File file = new File(path);
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            } else {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file);
            fw.write(str);
            fw.flush();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String readFile(String path) {
        String temp;
        String str = "";
        try {
            File file = new File(path);
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            while((temp = br.readLine()) != null){
                str += temp + "\n";
            }
            System.out.println(str);
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }
}
